package com.peng.stack_queue.linkedlist;

public class DoubleEndsQueue {
    
    private class Node {
        public int val;
        public Node last;
        public Node next;

        public Node(int val) {
            this.val = val;
        }
    }

    private Node tail;
    private Node head;

    public void addFromHead(int val) {
        Node node = new Node(val);
        if (head == null) {
            head = node;
            tail = node;
        } else {
            node.next = head;
            head.last = node;
            head = node;
        }
    }

    public void addFromBottom(int val) {
        Node node = new Node(val);
        if (head == null) {
            head = node;
            tail = node;
        } else {
            tail.next = node;
            node.last = tail;
            tail = node;
        }
    }

    public Integer popFromHead() {
        if (head == null) {
            return null;
        }
        Node popNode = head;

        if (head == tail) {
            head = null;
            tail = null;
        } else {
            head = head.next;

            head.last = null;

            popNode.next = null;
        }


        return popNode.val;
    }

    public Integer popFromBottom() {
        if (head == null) {
            return null;
        }
        Node popNode = tail;
        if (head == tail) {
            head = null;
            tail = null;
        } else {
            tail = tail.last;
            tail.next = null;

            popNode.last = null;
        }
        return popNode.val;
    }

    public void print() {
        Node cur = head;
        while (cur != null) {
            System.out.println(cur.val);
            cur = cur.next;
        }
    }
}
